/**
 * @desc:编辑退货弹框
 */

import React, { useState, useEffect, useRef } from "react";
import { Button, InputNumber, Popover, message } from 'antd';
import { cloneDeep, isEmpty } from 'lodash';
import CommonModal from '@/components/CommonModal';
import CommonTable from '@/components/CommonTable';
import CommonTag from '@/components/CommonTag';
import CommonLoading from '@/components/CommonLoading';
import ApplyReturnNextModal from './ApplayReturnNextModal'; 
import { refundOrderSave, zhifaRefundEdit } from '../../../service';
import { addCommas, formatZjfImg, formatHref, formatZjfHref } from '@/utils/utils.jsx';

import styles from './index.module.less';

//标签映射  goodsLabel  商品标签[1:拿货，2:库存，3:直发]
const TagMap = {
  1:'nahuo',
  2:'zifa',
  3:'cjzf',
}

export default ({ visible, item, expressList = [], handleOk, handleCancel }) => {

  const [loading, setLoading] = useState(false);
  const [list, setList] = useState([])
  const [nextVisible, setNextVisible] = useState(false);
  const [isDisabled, setDisabled] = useState(false);

  const deleteGoodsIds = useRef([]);

  const { channelId } = item;

  useEffect(() => {
    if(!isEmpty(item)){
      setList(item.refundOrderGoodsViewVOList || [])
    }
  }, [item])

  useEffect(() => {
    if(list.length){
      let btn = true;
      for(let i in list) {
        const item = list[i];
        if(item.applyRefundNum) {
          btn = false;
          break;
        }
      }
      setDisabled(btn)
    }else{
      setDisabled(true)
    }
  }, [list])

  const handleSaveData = async (val) => {
    // console.log(val,'val');
    // return
    setLoading(true);
    const params = {
      ...item,
      refundOrderGoodsList: list.filter(item=>item.applyRefundNum),
      refundOrderGoodsViewVOList: undefined,
      ...val,
    }
    const { success } = await refundOrderSave(params);
    setLoading(false);
    if(success) {
      message.success('编辑成功！');
      handleOk();
      setNextVisible(false)
    }
  }

  const columns = [
    { 
      title: '商品',
      dataIndex: 'goodsName',
      render: (text,v) => {
        const {orderChannel, goodsImage, storeId, ecGoodsImage, spuId, type, skuId, goodsLabel } = v
        // let imgSrc = '';//商品图片路径
        // if(goodsImage){
        //   imgSrc = formatZjfImg(goodsImage,storeId, 0, 64)
        // }else if(ecGoodsImage){
        //   imgSrc = ecGoodsImage
        // }else{
        //   imgSrc = 'https://imgniu.zhaojiafang.com/no-img64.jpg'
        // };
        const imgSrc = formatZjfImg(goodsImage,storeId, 0, 64);
        let detailSrc = null;//商品详情地址
        if(orderChannel){
           if(orderChannel == -1){
            detailSrc = formatZjfHref(skuId);//商城
           }else{
            detailSrc = formatHref(spuId, type, skuId);//三方
           }
        }
        return (
            <div style={{ display: 'flex', alignItems: 'center', width: '240px' }}>
              <Popover content={<div className='custom-ant-popver-content'><img src={imgSrc} alt=" " style={{width:'200px'}}/></div>}>
                <img src={imgSrc} alt="" className={styles.imgWrap} />
              </Popover>
              <div className={styles.goodsMsg}>
                <a href={detailSrc}>
                  <Popover content={<div className='custom-ant-popver-content'>{v.goodsName} {v.goodsSpec}</div>}>
                    <div className='textOverflowMultiOne common-color1'>
                      {v.goodsName}
                    </div>
                    <div className='textOverflowMultiOne commom-color4'>
                      {v.goodsSpec}
                    </div>
                  </Popover>
                </a>
                <div className='textOverflowMultiOne'>
                  商品编码：
                  {v.goodsId}
                </div>
                <CommonTag type ={TagMap[goodsLabel]}/>
                {v.isComposeGoods == 2 && <CommonTag type='zuhe' />}
              </div>
            </div>
        )
      }
    },
    {
      title: '供应商',
      dataIndex: 'storeName',
    },
    {
      title: '供应商价格',
      dataIndex: 'goodsPrice',
      render: text => {
        return (
          (text || text ==0 ) && <span className="common-color9">¥{addCommas(text)}</span>
        )
      }
    },
    {
      title: '已发货数量',
      dataIndex: 'shipNum',
    },
    {
      title: '可申请数量',
      dataIndex: 'canApplyNum',
    },
    {
      title: '申请数量',
      dataIndex: 'applyRefundNum',
      render: (text, v, index) => {
        return (
          <InputNumber disabled={!v.channelId || !v.canApplyNum} min={0} max={v.canApplyNum} onChange={(val) => handleChange(val, index)} value={text}/>
        )
      }
    },
    {
      title:'操作',
      dataIndex:'id',
      fixed:'right',
      render:text => <Button onClick={()=>handleDeleteApplyItem(text)} type='link'>删除</Button>
    }
  ]

  const handleDeleteApplyItem = (id) => {
    deleteGoodsIds.current = [...deleteGoodsIds.current, id];
    const arr = list.filter(item => item.id != id);
    setList(arr)
  }

  //点击输入申请数量
  const handleChange = (val, index) => {
    const arr = cloneDeep(list)
    arr[index]['applyRefundNum'] = val
    setList(arr)
  }

  //直发单编辑
  const handleEditzhifaRefundOrder = async (val) => {
    setLoading(true);
    const { data, success } = await zhifaRefundEdit(val);
    if (success) {
      message.success('编辑成功！');
      handleOk();
    } 
    setLoading(false);
  }

  const CommonTableProps = {
    data: list,
    columns,
    rowKey: 'goodsId',
  }

  const ApplyReturnProps = {
    visible: nextVisible,
    item,
    expressList,
    refundOrderGoodsIds:deleteGoodsIds.current,
    handleOk(val) {
      if(channelId === 0){
        handleEditzhifaRefundOrder(val);
      }else if(channelId){
        handleSaveData(val);
      }
    },
    handleCancel() {
      setNextVisible(false);
    }
  }

  return (
    <CommonModal
      title="编辑退货申请单"
      width="848px"
      visible={visible}
      onOk={()=>setNextVisible(true)}
      onCancel={handleCancel}
      footer={[<Button key='cancel' onClick={handleCancel}>取消</Button>,
               <Button key='next' onClick={()=>setNextVisible(true)} disabled={isDisabled}>下一步</Button>]}
    >
      <CommonTable { ...CommonTableProps } />
      {loading && <CommonLoading loading={true} />}
      {nextVisible && <ApplyReturnNextModal { ...ApplyReturnProps} /> }
    </CommonModal>
  )
}